﻿using UnityEngine;
using System.Collections;

public class UIFollowObj : MonoBehaviour {
	public Transform t_Target;
	public Camera c_MainCamera;
	public Camera c_UICamera;
	public Vector2 m_Offest = new Vector2();
	public Vector2 Offest{
		set{ m_Offest = value;}
		get{ return m_Offest;}
	}
	private Vector3 ViewPos;
	private Vector3 screenPos;

	public bool b_IsPlaying;
	public static UIFollowObj Init(GameObject uiobj,Transform target,Camera MainCamera,Camera UICamera){
		UIFollowObj uifo;
		uifo = uiobj.GetComponent<UIFollowObj>();
		if(uifo == null)
			uifo = uiobj.AddComponent<UIFollowObj>();
		uifo.init(target,MainCamera,UICamera);
		return uifo;
	}
	public static UIFollowObj Init(GameObject uiobj,Transform target,Camera UICamera){
		return Init(uiobj,target,UICamera,UICamera);
	}
	public static void RemoveFollow(GameObject uiobj){
		GameObject.Destroy (uiobj);
	}
	void init(Transform target,Camera maincamera,Camera uicamera){
		t_Target = target;
		c_MainCamera = maincamera;
		c_UICamera = uicamera;
		b_IsPlaying = true;
	}
	void LateUpdate () {
		if(b_IsPlaying && t_Target!=null){
			Vector3 tarpos;
			tarpos = t_Target.position;
			tarpos.x += Offest.x;
			tarpos.y += Offest.y;
			screenPos = c_MainCamera.WorldToScreenPoint (tarpos);
			ViewPos = c_UICamera.ScreenToWorldPoint (new Vector3 (screenPos.x,screenPos.y,c_UICamera.nearClipPlane));
			ViewPos.z = 0;
			transform.position = ViewPos;
		}
	}

}
